<?php
error_reporting(E_ALL);

include_once 'common_classes.php';
include_once 'common_functions.php';

ini_set("session.gc_maxlifetime", "10800");

session_start();

if(IsSet($_SESSION['candidate']) && IsSet($_SESSION['election']) && IsSet($_SESSION['candidate_id']))
{
	$questions = QueryBuilder::getAllQuestionsForCurrentElection();
	$count = count($questions[0]); // QueryBuilder::getCountOfQuestionsForCurrentElection();
	
	$input = $_POST;
	
	// [index][0] = Q_id
	// [index][1] = answer
	// [index][2] = important
	// [index][3] = explanation
	$answers[0][0] = 0;
	
	$importantquestions = 0;
	
	for($i = 0; $i < $count; $i++) {
		$questionID = $questions[1][$i];
		
		if(IsSet($input[$questionID]))
			$answerCode = $input[$questionID];
		else
			$answerCode = 'C';
			
		$answerCode = translateCode($answerCode);
		
		if(IsSet($input['important_' . $questionID])) {
			$importantquestions++;
			$isImportant = 1;
		}
		else
			$isImportant = 0;
			
		if(IsSet($input['ef_' . $questionID])) 
			$explanation = $input['ef_' . $questionID];
		else
			$explanation = "";
			
		$answers[$i][0] = $questionID;
		$answers[$i][1] = $answerCode;
		$answers[$i][2] = $isImportant;	
		$answers[$i][3] = $explanation;
	}
	
	if($importantquestions == Config::number_of_important_questions)  
		QueryBuilder::writeAnswers($answers, $count, $_SESSION['candidate_id']);
		
	header('location: candidate_login.php');
}
else
	header('location: candidate_login.php');